﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Whoever.Patterns.Business;

using Comswing.Data;
using Comswing.Data.Repositories;
using Comswing.Business.Entities;
using Comswing.Business.Entities.Enumerables;

namespace Comswing.Business
{
    public class SwingManager : Manager<Swing>
    {
        public SwingManager()
            : base(new SwingRepository())
        {

        }

        public override void Insert(Swing item)
        {
            item.Active = true;
            switch (item.TimeLapse)
            {
                case SwingTimeLapse.Day:
                    {
                        item.StartDate = DateTime.Now.Date;
                        item.FinishDate = DateTime.Now.Date.AddDays(1);
                        break;
                    }
                case SwingTimeLapse.Week:
                    {
                        item.StartDate = DateTime.Now.Date;
                        item.FinishDate = DateTime.Now.Date.AddDays(7);
                        break;
                    }
                case SwingTimeLapse.Month:
                    {
                        item.StartDate = DateTime.Now.Date;
                        item.FinishDate = DateTime.Now.Date.AddDays(30);
                        break;
                    }
            }

            Repository.Insert(item);
        }

        public void Finish(Swing swing)
        {
            var swingManager = new SwingManager();
            var userSwingManager = new UserSwingManager();

            var userSwings = userSwingManager.GetAll();
            UserSwing userSwing = null;

            var randomIdFactory = new Random();
            var randomId = 0;
            var maxIdRangue = userSwings.Max(e => e.UserId);

            //Check for a real random Algorythm
            randomId = randomIdFactory.Next(1, maxIdRangue);
            userSwing = userSwings.Where(e => e.SwingId == swing.Id && e.UserId == randomId).Single();
            while (userSwing == null)
            {
                randomId = randomIdFactory.Next(1, maxIdRangue);
                userSwing = userSwings.Where(e => e.SwingId == swing.Id && e.UserId == randomId).Single();
            }

            if (userSwing != null)
            {
                userSwing.Winner = true;
                swing.Active = false;
                swingManager.Update(swing);
                userSwingManager.Update(userSwing);
            }
            else
                throw new Exception("Cannot get a random winner");
        }

        public IEnumerable<Swing> GetActives()
        {
            var swingManager = new SwingManager();

            return swingManager.GetAll().Where(e => e.Active);
        }
    }
}
